import request from '@/utils/request'
import { LOGIN, USERINFO, GET_CHANNEL, GET_ARTICLE } from '@/store/actionTypes'
import { setToken } from '@/utils/storage'

export const login = (data) => {
  console.log('actions', data)
  return async dispatch => {
    const res = await request.post('authorizations', data)
    dispatch({
      type: LOGIN,
      payload: res.data.token
    })
    setToken(res.data.token)
  }
}
export const getUserInfo = () => {
  return async dispatch => {
    const res = await request.get('user')
    dispatch({
      type: USERINFO,
      payload: res.data
    })
  }
}
export const checkOut = () => ({
  type: 'OUT'
})
// 获取频道
export const getChannel = () => {
  return async dispatch => {
    const res = await request.get('channels')
    dispatch({
      type: GET_CHANNEL,
      payload: res.data.channels
    })
  }
}
// 获取文章
export const getArticle = (params = {}) => {
  return async dispatch => {
    const res = await request.get('mp/articles', {
      params: {
        status: params.status,
        channel_id: params.channel_id,
        begin_pubdate: params.begin_pubdate,
        end_pubdate: params.end_pubdate,
        page: params.page,
        per_page: 5
      }
    })
    dispatch({
      type: GET_ARTICLE,
      payload: res.data
    })
  }
}
export const del = (id) => {
  return async dispatch => {
    await request.delete('mp/articles/' + id)
  }
}
export const postArt = (data, draft) => {
  return async dispatch => {
    await request.post('mp/articles?draft=' + draft, data)
  }
}
export const getArt = (id) => {
  return async dispatch => {
    return await request.get(`mp/articles/${id}`)
  }
}
export const putArt = (data, draft, id) => {
  return async dispatch => {
    return await request.put(`mp/articles/${id}?draft=` + draft, data)
  }
}
